package com.wjk.test;

/**
 * @author : RobertWei
 * time: 2021/9/24    14:19
 * description:
 */

public class Demo {

    /**
     * 删除链表后n位
     * @param head 链表的头节点
     * @param n 要删除的位置
     * @return 返回删除之后链表头节点
     */
    public ListNode removeNthFromEnd(ListNode head , int n){

        ListNode first = head;
        ListNode target = head;

        //一号指针先向前走 n 步
        for (int i = 0; i < n; i++) {
            if (first.next == null){
                return head;
            }
            first = first.next;
        }

        // 同时移动, 当一号指针走到最后一个退出循环
        while (first.next != null) {
            target = target.next;
            first = first.next;
        }

        //此时二号指针指向要删除的前一位
        //修改二号指针的next
        target.next = target.next.next;

        return head;

    }

}

class ListNode{

    int val;
    ListNode next;

    public ListNode(int val){
        this.val = val;
        next = null;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
